package com.jcsz.gulimall.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import com.jcsz.common.exception.BizCodeEnume;
import com.jcsz.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * @className: SentinelGateWayConfig
 * @author: 一把Po吉他
 * @date: 2022/11/20 12:11
 * @version: 1.0
 **/
@Configuration
@Slf4j
public class SentinelGateWayConfig {
    public SentinelGateWayConfig() {
        GatewayCallbackManager.setBlockHandler((exchange, t) -> {
            // 网关限流了请求 就会回调这个方法
            R error = R.error(BizCodeEnume.TOO_MANY_REQUEST.getCode(), BizCodeEnume.TOO_MANY_REQUEST.getMsg());
            String errJson = JSON.toJSONString(error);
            log.info("网关限流....");
            Mono<ServerResponse> body = ServerResponse.ok().body(Mono.just(errJson), String.class);
            return body;
        });
    }
}
